package com.ews.auth.util;

import com.alibaba.fastjson.JSONObject;

import org.apache.http.HttpEntity;
import org.apache.http.NameValuePair;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.utils.URIBuilder;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicHeader;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;

import java.io.*;
import java.net.ConnectException;
import java.net.SocketTimeoutException;
import java.net.URL;
import java.net.URLConnection;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * HttpClient发送GET、POST请求
 *
 * @Author libin
 * @CreateDate 2018.5.28 16:56
 */
public class HttpClientUtils {
	/**
	 * 返回成功状态码
	 */
	private static final int SUCCESS_CODE = 200;

	/**
	 * 发送GET请求
	 *
	 * @param url               请求url
	 * @param nameValuePairList 请求参数
	 * @return JSON或者字符串
	 * @throws Exception
	 */
	public static Object sendGet(String url, List<NameValuePair> nameValuePairList) throws Exception {
		JSONObject jsonObject = null;
		CloseableHttpClient client = null;
		CloseableHttpResponse response = null;
		try {
			client = HttpClients.createDefault();
			URIBuilder uriBuilder = new URIBuilder(url);
			if (nameValuePairList != null && nameValuePairList.size() > 0) {
				uriBuilder.addParameters(nameValuePairList);
			}
			// 创建HttpGet
			HttpGet httpGet = new HttpGet(uriBuilder.build());
			// 设置请求头部编码
			httpGet.setHeader(new BasicHeader("Content-Type", "application/x-www-form-urlencoded; charset=utf-8"));
			// 设置返回编码
			httpGet.setHeader(new BasicHeader("Accept", "text/plain;charset=utf-8"));
			response = client.execute(httpGet);
			int statusCode = response.getStatusLine().getStatusCode();
			if (SUCCESS_CODE == statusCode) {
				HttpEntity entity = response.getEntity();
				String result = EntityUtils.toString(entity, "UTF-8");
				try {
					jsonObject = JSONObject.parseObject(result);
					return jsonObject;
				} catch (Exception e) {
					return result;
				}
			} else {
				//log.error("HttpClientService-line: {}, errorMsg{}", 97, "GET请求失败！");
			}
		} catch (Exception e) {
			//log.error("HttpClientService-line: {}, Exception: {}", 100, e);
		} finally {
			if (response != null) {
				response.close();
			}
			if (client != null) {
				client.close();
			}
		}
		return null;
	}

	/**
	 * 发送POST请求
	 *
	 * @param url
	 * @param nameValuePairList
	 * @return JSON或者字符串
	 * @throws Exception
	 */
	public static Object sendPost(String url, List<NameValuePair> nameValuePairList) throws Exception {
		JSONObject jsonObject = null;
		CloseableHttpClient client = null;
		CloseableHttpResponse response = null;
		try {
			// 创建一个httpclient对象
			client = HttpClients.createDefault();
			HttpPost post = new HttpPost(url);
			// 包装成一个Entity对象
			if (nameValuePairList != null && nameValuePairList.size() > 0) {
				StringEntity entity = new UrlEncodedFormEntity(nameValuePairList, "UTF-8");
				post.setEntity(entity);
			}
			post.setHeader(new BasicHeader("Content-Type", "application/x-www-form-urlencoded;charset=utf-8"));
			response = client.execute(post);
			int statusCode = response.getStatusLine().getStatusCode();
			if (SUCCESS_CODE == statusCode) {
				String result = EntityUtils.toString(response.getEntity(), "UTF-8");
				try {
					jsonObject = JSONObject.parseObject(result);
					return jsonObject;
				} catch (Exception e) {
					return result;
				}
			} else {
				//log.error("HttpClientService-line: {}, errorMsg：{}", 146, "POST请求失败！");
			}
		} catch (Exception e) {
			//log.error("HttpClientService-line: {}, Exception：{}", 149, e);
		} finally {
			if (response != null) {
				response.close();
			}
			if (client != null) {
				client.close();
			}
		}
		return null;
	}



	public static Object sendGet(String url) throws Exception {
		return sendGet(url, new ArrayList<>());
	}

	public static Object sendPost(String url) throws Exception {
		return sendPost(url, new ArrayList<>());
	}

	public static Object sendPost(String url, Map<String, String> params) throws Exception {
		return sendPost(url, HttpClientUtils.getParams(params));
	}

	public static Object sendGet(String url, Map<String, String> params) throws Exception {
		return sendPost(url, HttpClientUtils.getParams(params));
	}

	/**
	 * 组织请求参数{参数名和参数值下标保持一致}
	 *
	 * @param params 参数名数组
	 * @param values 参数值数组
	 * @return 参数对象
	 */
	public static List<NameValuePair> getParams(Object[] params, Object[] values) {
		/**
		 * 校验参数合法性
		 */
		boolean flag = params.length > 0 && values.length > 0 && params.length == values.length;
		if (flag) {
			List<NameValuePair> nameValuePairList = new ArrayList<>();
			for (int i = 0; i < params.length; i++) {
				nameValuePairList.add(new BasicNameValuePair(params[i].toString(), values[i].toString()));
			}
			return nameValuePairList;
		} else {
			//log.error("HttpClientService-line: {}, errorMsg：{}", 197, "请求参数为空且参数长度不一致");
		}
		return null;
	}

	/**
	 * 组织请求参数{参数名和参数值下标保持一致}
	 *
	 * @param params 参数Map
	 * @return 参数对象
	 */
	public static List<NameValuePair> getParams(Map<String, String> params) {
		/**
		 * 校验参数合法性
		 */
		if (params != null && params.size() > 0) {
			List<NameValuePair> nameValuePairList = new ArrayList<>();
			for (String key : params.keySet()) {
				String value = params.get(key);
				nameValuePairList.add(new BasicNameValuePair(key, value));
			}
			return nameValuePairList;
		} else {
			//log.error("HttpClientService-line: {}, errorMsg：{}", 197, "请求参数为空且参数长度不一致");
		}
		return null;
	}


	/**
	 * 向指定 URL 发送GET方法的请求
	 *
	 * @param url 发送请求的 URL
	 * @param param 请求参数，请求参数应该是 name1=value1&name2=value2 的形式。
	 * @param contentType 编码类型
	 * @return 所代表远程资源的响应结果
	 */
	public static String sendGet(String url, String param, String contentType)
	{
		StringBuilder result = new StringBuilder();
		BufferedReader in = null;
		try
		{
			String urlNameString = url + "?" + param;
			//log.info("sendGet - {}", urlNameString);
			URL realUrl = new URL(urlNameString);
			URLConnection connection = realUrl.openConnection();
			connection.setRequestProperty("accept", "*/*");
			connection.setRequestProperty("connection", "Keep-Alive");
			connection.setRequestProperty("user-agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)");
			connection.connect();
			in = new BufferedReader(new InputStreamReader(connection.getInputStream(), contentType));
			String line;
			while ((line = in.readLine()) != null)
			{
				result.append(line);
			}
			//log.info("recv - {}", result);
		}
		catch (ConnectException e)
		{
			//log.error("调用HttpUtils.sendGet ConnectException, url=" + url + ",param=" + param, e);
		}
		catch (SocketTimeoutException e)
		{
			//log.error("调用HttpUtils.sendGet SocketTimeoutException, url=" + url + ",param=" + param, e);
		}
		catch (IOException e)
		{
			//log.error("调用HttpUtils.sendGet IOException, url=" + url + ",param=" + param, e);
		}
		catch (Exception e)
		{
			//log.error("调用HttpsUtil.sendGet Exception, url=" + url + ",param=" + param, e);
		}
		finally
		{
			try
			{
				if (in != null)
				{
					in.close();
				}
			}
			catch (Exception ex)
			{
				//log.error("调用in.close Exception, url=" + url + ",param=" + param, ex);
			}
		}
		return result.toString();
	}


}